import 'dart:io';
import 'dart:math';

import 'package:badges/badges.dart' as badges;
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:jet_rails/jr_app/jr_views/jr_home/jr_home_controller.dart';
import 'package:jet_rails/jr_app/jr_widgets/jr_app_bar.dart';
import 'package:jet_rails/jr_app/jr_widgets/jr_buttons.dart';
import 'package:jet_rails/jr_app/jr_widgets/jr_scaffold.dart';
import 'package:jet_rails/jr_utils/jr_snippet.dart';
import 'package:jet_rails/jr_utils/jr_toast.dart';

class JrActivityPostView extends StatefulWidget {
  const JrActivityPostView({super.key});

  @override
  State<JrActivityPostView> createState() => _JrActivityPostViewState();
}

class _JrActivityPostViewState extends State<JrActivityPostView> {
  JrHomeController controller = Get.find<JrHomeController>();
  TextEditingController teamNameController = TextEditingController();
  TextEditingController timeController = TextEditingController();
  TextEditingController placeController = TextEditingController();
  TextEditingController descriptionController = TextEditingController();

  int maxTitleLength = 100;
  int maxContentLength = 600;

  @override
  void initState() {
    super.initState();
    Get.find<JrHomeController>().postImageList.value.clear();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).unfocus();
      },
      child: JrScaffold(
        appBar: JrAppBar(
          title: 'Create event',
        ),
        body: SingleChildScrollView(
            physics: const ClampingScrollPhysics(),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                    margin: EdgeInsets.only(top: 16.h, bottom: 30.h, left: 16.w, right: 16.w),
                    child: Stack(children: [
                      Container(
                        padding: const EdgeInsets.all(16),
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(12.r),
                            boxShadow: [
                              BoxShadow(color: Colors.white24, offset: Offset(0, 0.5.r), blurRadius: 1.r),
                            ],
                            gradient: const LinearGradient(
                                begin: Alignment.topLeft,
                                end: Alignment.bottomRight,
                                colors: [Color(0xFF693F73), Color(0xFF8F4D9A)])),
                        child: Column(
                          children: [
                            TextField(
                              decoration: InputDecoration(
                                labelStyle: TextStyle(color: Colors.white, fontSize: 16.r),
                                labelText: 'Team Name: ',
                                border: InputBorder.none,
                              ),
                              style: TextStyle(color: Colors.white, fontSize: 16.r),
                              maxLines: 1,
                              controller: teamNameController,
                              onChanged: (value) {
                                if (value.length >= maxTitleLength) {
                                  teamNameController.text = value.substring(0, maxTitleLength);
                                  teamNameController.selection =
                                      TextSelection.fromPosition(TextPosition(offset: teamNameController.text.length));
                                }
                              },
                            ),
                            TextField(
                              decoration: InputDecoration(
                                labelText: 'Time: ',
                                labelStyle: TextStyle(color: Colors.white60, fontSize: 14.r),
                                border: InputBorder.none,
                              ),
                              maxLines: 1,
                              style: TextStyle(color: Colors.white60, fontSize: 14.r),
                              controller: timeController,
                              onChanged: (value) {
                                if (value.length >= maxTitleLength) {
                                  timeController.text = value.substring(0, maxTitleLength);
                                  timeController.selection =
                                      TextSelection.fromPosition(TextPosition(offset: timeController.text.length));
                                }
                              },
                            ),
                            TextField(
                              decoration: InputDecoration(
                                labelText: 'Place: ',
                                labelStyle: TextStyle(color: Colors.white60, fontSize: 14.r),
                                border: InputBorder.none,
                              ),
                              maxLines: 1,
                              style: TextStyle(color: Colors.white60, fontSize: 14.r),
                              controller: placeController,
                              onChanged: (value) {
                                if (value.length >= maxTitleLength) {
                                  placeController.text = value.substring(0, maxTitleLength);
                                  placeController.selection =
                                      TextSelection.fromPosition(TextPosition(offset: placeController.text.length));
                                }
                              },
                            ),
                            TextField(
                              decoration: InputDecoration(
                                labelText: 'Description: ',
                                labelStyle: TextStyle(color: Colors.white60, fontSize: 14.r),
                                border: InputBorder.none,
                              ),
                              maxLines: 1,
                              style: TextStyle(color: Colors.white60, fontSize: 14.r),
                              controller: descriptionController,
                              onChanged: (value) {
                                if (value.length >= maxTitleLength) {
                                  descriptionController.text = value.substring(0, maxTitleLength);
                                  descriptionController.selection = TextSelection.fromPosition(
                                      TextPosition(offset: descriptionController.text.length));
                                }
                              },
                            )
                          ],
                        ),
                      ),
                      Positioned(
                        right: 0,
                        bottom: 0,
                        child: Transform(
                          alignment: Alignment.center,
                          transform: Matrix4.rotationY(pi),
                          child: Image.asset('assets/images/icon_rails.png', height: 40.h),
                        ),
                      )
                    ])),
                buildImagePicker(),
                SizedBox(height: 110.h),
                Column(
                  children: [
                    const SizedBox(width: double.infinity),
                    badges.Badge(
                      ignorePointer: true,
                      badgeStyle: const badges.BadgeStyle(badgeColor: Colors.transparent),
                      position: badges.BadgePosition.topEnd(top: -30.h, end: -55.w),
                      badgeContent: const CostBadge(),
                      child: JrStyledButton(
                        width: 130,
                        text: 'Pay and publish',
                        onTap: () {
                          if (teamNameController.text.isEmpty) {
                            JrToast.show('Please input team name.');
                            return;
                          }
                          if (descriptionController.text.isEmpty) {
                            JrToast.show('Please input description.');
                            return;
                          }
                          if (controller.postImageList.isEmpty) {
                            JrToast.show('Please add image.');
                            return;
                          }
                          controller.createEvent(teamNameController.text, descriptionController.text,
                              time: timeController.text, place: placeController.text);
                        },
                      ),
                    ),
                    SizedBox(height: 10.h),
                  ],
                )
              ],
            )),
      ),
    );
  }

  buildImagePicker() {
    Widget addWidget = GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () async {
        Get.find<JrHomeController>().addPostImage();
      },
      child: Container(
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: const Color(0xFF3D3066),
          borderRadius: BorderRadius.circular(12.r),
        ),
        margin: EdgeInsets.only(bottom: 32.h, left: 20.w, right: 0.w),
        width: 104.w,
        height: 110.h,
        child: SizedBox(
          width: 24.w,
          height: 20.h,
          child: SvgPicture.asset('assets/svg/icon_add_image.svg'),
        ),
      ),
    );

    return Obx(() {
      List<Widget> children = [];
      for (var item in Get.find<JrHomeController>().postImageList) {
        children.add(Container(
          margin: EdgeInsets.only(bottom: 32.h, left: 20.w, right: 0.w),
          child: Stack(children: [
            Container(
              width: 104.w,
              height: 110.h,
              clipBehavior: Clip.hardEdge,
              decoration: BoxDecoration(borderRadius: BorderRadius.circular(12.r)),
              child: Image.file(
                File(item),
                fit: BoxFit.fill,
              ),
            ),
            Positioned(
              right: 0,
              top: 0,
              child: GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  Get.find<JrHomeController>().postImageList.value.remove(item);
                  Get.find<JrHomeController>().postImageList.refresh();
                },
                child: Container(
                  width: 24.w,
                  height: 24.h,
                  decoration: BoxDecoration(
                      color: Colors.black54,
                      borderRadius:
                          BorderRadius.only(bottomLeft: Radius.circular(8.r), topRight: Radius.circular(12.r))),
                  child: Center(
                      child: Icon(
                    Icons.delete_forever_outlined,
                    size: 18.r,
                    color: Colors.white60,
                  )),
                ),
              ),
            ),
          ]),
        ));
      }

      if (children.length < 3) {
        children.add(addWidget);
      }
      return SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: Row(
          children: children,
        ),
      );
    });
  }
}

class CostBadge extends StatefulWidget {
  final bool? mirrorBg;
  const CostBadge({Key? key, this.mirrorBg}) : super(key: key);

  @override
  State<CostBadge> createState() => _CostBadgeState();
}

class _CostBadgeState extends State<CostBadge> {
  @override
  Widget build(BuildContext context) {
    Widget bg = Image.asset('assets/webp/img_bubble_bg.webp', height: 30.h, width: 65.w);
    if (widget.mirrorBg == true) {
      bg = Transform(alignment: Alignment.center, transform: Matrix4.rotationY(pi), child: bg);
    }

    return SizedBox(
      height: 30.h,
      width: 65.w,
      child: Stack(children: [
        bg,
        Obx(() {
          final controller = Get.find<JrHomeController>();
          return Center(
              child: controller.haveFreeTickets
                  ? Text('Free x${controller.freeTickets}',
                      style:
                          JrSnippets.commonTextStyle.merge(TextStyle(color: const Color(0xFF916EFF), fontSize: 12.sp)))
                  : Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Image.asset(
                          'assets/webp/icon_coin.webp',
                          height: 16.sp,
                        ),
                        SizedBox(width: 2.w),
                        Text('${JrHomeController.postCost}coins',
                            style: TextStyle(color: const Color(0xFF916EFF), fontSize: 12.sp))
                      ],
                    ));
        })
      ]),
    );
  }
}
